package com.xiyili.osc.ui.news;

import java.io.IOException;

import me.imid.swipebacklayout.lib.app.SwipeBackActivity;
import net.oschina.app.AppException;
import net.oschina.app.bean.CommentList;
import net.oschina.app.bean.News;
import net.oschina.app.bean.URLs;
import net.oschina.app.common.PagingInfo;
import net.oschina.app.common.UIHelper;
import net.oschina.app.requests.PagingRequest;
import net.oschina.app.ui.ToastUtils;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.NavUtils;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.xiyili.osc.G;
import com.xiyili.osc.R;
import com.xiyili.osc.ui.CommentAdapter;

/**
 * 新闻详情
 * @author banxi1988
 * @since 2013-09-01
 * 
 */
public class NewsDetailActivity extends SwipeBackActivity {
	//XIYILI
	private ViewPager mViewPager;
	private int _newsId;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.news_v2_detail_activity);

		mViewPager = (ViewPager)findViewById(R.id.pager);
		mViewPager.setAdapter(new NewsDetailPagerAdapter(getSupportFragmentManager()));

		getActionBar().setTitle("资讯详情");
		getActionBar().setDisplayHomeAsUpEnabled(true);
		Intent intent = getIntent();
		_newsId = intent.getIntExtra("news_id", 0);
		

	}

	public class NewsDetailPagerAdapter extends FragmentPagerAdapter{

		public NewsDetailPagerAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public Fragment getItem(int positon) {
			if(positon == 0){
				return NewsDetailActicleFragment.newInstance(getIntent().getExtras());
			}else if(positon == 1){
				return NewsDetailCommentListFragment.newInstance(_newsId);
			}else{
				Log.wtf("GET_ITEM", "what a fuck!");
				return null;
			}
		}

		@Override
		public int getCount() {
			return 2;
		}
		
	}
	
	public static class NewsDetailActicleFragment extends Fragment{
		
		public NewsDetailActicleFragment(){
			// empty constructor need for super
		}
		
		// VIEWS
		private TextView mTitle;
		private TextView mAuthor;
		private TextView mPubDate;
		private TextView mCommentCount;
		
		private WebView mWebView;

		// VALUE FIELDS
		
		private int newsId;
		private String newsTitle;
		private String newsAuthor;
		private String newsPubDate;
		private int newsCommentCount;
		
		private News newsDetail;
		
		public static NewsDetailActicleFragment newInstance(Bundle args){
			NewsDetailActicleFragment f = new NewsDetailActicleFragment();
			if(args != null){
				f.setArguments(args);
			}
			return f;
		}
		
		@Override
		public void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			if(getArguments() != null){
				Bundle intent = getArguments();
				newsId = intent.getInt("news_id", 0);
				newsTitle = intent.getString("news_title");
				newsAuthor = intent.getString("news_author");
				newsPubDate = intent.getString("news_pubDate");
				newsCommentCount = intent.getInt("news_comment_count",0);
			}
		}
		
		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View layout = inflater.inflate(R.layout.news_v2_detail_article_fragment, container, false);
			
			mTitle = (TextView)layout.findViewById(R.id.news_detail_title);
			mAuthor = (TextView)layout.findViewById(R.id.news_detail_author);
			mPubDate = (TextView) layout.findViewById(R.id.news_detail_date);
			mCommentCount = (TextView) layout.findViewById(R.id.news_detail_commentcount);
			mTitle.setText(newsTitle);
			mAuthor.setText(newsAuthor);
			mPubDate.setText(newsPubDate);
			mCommentCount.setText(newsCommentCount+"");
			
			mWebView = (WebView) layout.findViewById(R.id.news_detail_webview);
			mWebView.getSettings().setSupportZoom(true);
			mWebView.getSettings().setBuiltInZoomControls(false);
			mWebView.getSettings().setDefaultFontSize(15);
	        UIHelper.addWebImageShow(getActivity(), mWebView);
	        initData();
			
			return layout;
		}
		
		protected void handleResponse(String response) {
			try {
				newsDetail = News.parse(response);
				String body = UIHelper.WEB_STYLE + newsDetail.getBody();
				// 读取用户设置：是否加载文章图片--默认有wifi下始终加载图片
				
				
				boolean isLoadImage = G.isWifi(getActivity());
					
				if (isLoadImage) {
					// 过滤掉 img标签的width,height属性
					body = body.replaceAll(
							"(<img[^>]*?)\\s+width\\s*=\\s*\\S+", "$1");
					body = body.replaceAll(
							"(<img[^>]*?)\\s+height\\s*=\\s*\\S+", "$1");

					// 添加点击图片放大支持
					body = body.replaceAll("(<img[^>]+src=\")(\\S+)\"",
							"$1$2\" onClick=\"javascript:mWebViewImageListener.onImageClick('$2')\"");

				} else {
					// 过滤掉 img标签
					body = body.replaceAll("<\\s*img\\s+([^>]*)\\s*>", "");
				}

//				// 更多关于***软件的信息
//				String softwareName = newsDetail.getSoftwareName();
//				String softwareLink = newsDetail.getSoftwareLink();
//				if (!StringUtils.isEmpty(softwareName)
//						&& !StringUtils.isEmpty(softwareLink))
//					body += String
//							.format("<div id='oschina_software' style='margin-top:8px;color:#FF0000;font-weight:bold'>更多关于:&nbsp;<a href='%s'>%s</a>&nbsp;的详细信息</div>",
//									softwareLink, softwareName);
	//
//				// 相关新闻
//				if (newsDetail.getRelatives().size() > 0) {
//					String strRelative = "";
//					for (Relative relative : newsDetail.getRelatives()) {
//						strRelative += String
//								.format("<a href='%s' style='text-decoration:none'>%s</a><p/>",
//										relative.url, relative.title);
//					}
//					body += String.format(
//							"<p/><hr/><b>相关资讯</b><div><p/>%s</div>",
//							strRelative);
//				}

				body += "<div style='margin-bottom: 80px'/>";

				System.out.println(body);

				mWebView.loadDataWithBaseURL(null, body, "text/html",
						"utf-8", null);
				mWebView.setWebViewClient(UIHelper.getWebViewClient());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (AppException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
		// 初始化控件数据
		private void initData() {
			String url = URLs.NEWS_DETAIL+"?id="+newsId;
			StringRequest request = new StringRequest(url, new Response.Listener<String>() {

				@Override
				public void onResponse(String response) {
					handleResponse(response);
					
				}
			}, new Response.ErrorListener() {

				@Override
				public void onErrorResponse(VolleyError error) {
					// TODO Auto-generated method stub
					
				}
			});
			G.getRequestQueue(getActivity()).add(request);
			
		
		}


		
	}
	
	public static class NewsDetailCommentListFragment extends Fragment{
		
		public NewsDetailCommentListFragment(){
			// empty constuctor need for super
		}
		private ListView mCommentListView;
		
		private int curId;
		private int curCatalog = CommentList.CATALOG_NEWS;
		
		public static NewsDetailCommentListFragment newInstance(int newsId){
			NewsDetailCommentListFragment f = new NewsDetailCommentListFragment();
			Bundle args = new Bundle();
			args.putInt("news_id", newsId);
			f.setArguments(args);
			return f;
		}
		
		@Override
		public void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			
			if(getArguments() != null){
				curId = getArguments().getInt("news_id");
			}
		}
		
		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View layout = inflater.inflate(R.layout.news_v2_detail_comment_list_fragment, container, false);
	        mCommentListView = (ListView) layout.findViewById(R.id.comment_list_listview);
	        mCommentListView.setEmptyView(layout.findViewById(R.id.empty));
			initCommentData();
			return layout;
			
		}
		
		protected void handleCommentListResponse(String response) {
			try {
				CommentList commentList = CommentList.parse(response);
				ListAdapter adapter = new CommentAdapter(getActivity(), commentList.getCommentlist(),
						R.layout.comment_v2_list_item);
				mCommentListView.setAdapter(adapter);
				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (AppException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
		// 初始化评论数据
		private void initCommentData() {
			
			PagingInfo pi = new PagingInfo(0, curCatalog);
			String url = URLs.COMMENT_LIST+"?id="+curId;
			PagingRequest request = new PagingRequest(url, pi, new Response.Listener<String>() {

				@Override
				public void onResponse(String response) {
					handleCommentListResponse(response);
					
				}
			}, new Response.ErrorListener() {

				@Override
				public void onErrorResponse(VolleyError error) {
					ToastUtils.showFailure(getActivity(), "评论加载失败,"+error.getMessage());
					
				}
			});
			G.getRequestQueue(getActivity()).add(request);
			
			
		}

	}
	
	
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()){
		case android.R.id.home:
			NavUtils.navigateUpFromSameTask(this);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
}
